package com.Tadama.Forms;

import java.io.IOException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.List;
import com.Tadama.MIDlet.TadamaMIDlet;
import com.Tadama.Utility.CommandBuilder;
import com.Tadama.Bean.beUsuario;

public class frmLogin extends Form implements CommandListener{
    private TadamaMIDlet mainMidlet;
    private TextField tfUsuario;
    private TextField tfClave;
    private Alert alerta;
    
    private static final Command cmExit = CommandBuilder.getExit();
    private static final Command cmStoreLogin = CommandBuilder.getLogin();
    private static final Command cmOk = CommandBuilder.getOk();
    private static final Command cmAtras= CommandBuilder.getback();
    
    public frmLogin(TadamaMIDlet Midlet) throws IOException{
        super("Autenticación Usuario");
        this.mainMidlet = Midlet;
        init();
    }
    
    private void init() throws IOException{
        tfUsuario= new TextField("Usuario", "llpz", 6, TextField.ANY);
        tfClave= new TextField("Clave", "12345678", 10, TextField.PASSWORD);
        this.append(tfUsuario);
        this.append(tfClave);
        this.addCommand(cmStoreLogin);
        this.addCommand(cmExit);
        this.setCommandListener(this);
    }
    public void commandAction(Command c, Displayable d) {
        if(d==this){
            if (c == cmExit) {
                mainMidlet.destroyApp(true);
            }
            if(c==cmStoreLogin)
            {
                beUsuario Usuario = new beUsuario();
                Usuario.setUsuario(tfUsuario.getString().trim());
                Usuario.setPassword(tfClave.getString().trim());
                String imei = "1234567890";
                alerta = Usuario.validaUsuario(Usuario.getUsuario(), Usuario.getPassword(), imei);
                Display.getDisplay(mainMidlet).setCurrent(getAlerta(), this);
            }
        }
        if(d==alerta)
        {
            if(c==cmOk && AlertType.INFO==alerta.getType())
                Display.getDisplay(mainMidlet).setCurrent(new lstMenu(mainMidlet,"Menu Principal",List.IMPLICIT));
            if(c==cmAtras && AlertType.ERROR==alerta.getType())
                Display.getDisplay(mainMidlet).setCurrent(this);
        }
    }
    public Alert getAlerta() {
        if (alerta.getType() == AlertType.INFO) {
            alerta.addCommand(cmOk);
            alerta.setCommandListener(this);
        }
        if (alerta.getType() == AlertType.ERROR) {
            alerta.addCommand(cmAtras);
            alerta.setCommandListener(this);
        }
        return alerta;
    }   
}